package offer;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class offerII_0081 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result=new LinkedList<>();
        List<Integer> path=new LinkedList<>();
        search(result,path,target,candidates,0,0);
        return result;
    }
    public void search(List<List<Integer>> result,List<Integer> path,int target,int[] candidates,int index,int sum){
        if(sum==target){
            result.add(new ArrayList<>(path));
            return;
        }
        if(index==candidates.length||sum>target){
            return;
        }
        path.add(candidates[index]);
        search(result,path,target,candidates,index,sum+candidates[index]);
        if(target<sum+candidates[index]) search(result,path,target,candidates,index+1,sum+candidates[index]);
        path.remove(path.size()-1);
        search(result,path,target,candidates,index+1,sum);
    }
}
